import os
import json 
from pptx import Presentation
from APP.config.log_conf import log
from xinference.client.restful.restful_client import (
  Client,
  RESTfulChatModelHandle,
)
from xinference.client import RESTfulClient
from openai import OpenAI

class AiPPTServices:

    async def chat_llm(self,query: str): 
        # 百炼鉴权相关，从环境变量读取
        # xinference_client = RESTfulClient(base_url='http://10.191.62.233:5997')
        # xinference_model = xinference_client.get_model('deepseek-chat')

        # resp = xinference_model.chat(
        #     messages=[{"role": "system", "content": "You are a helpful assistant"}, {"role": "user", "content": query}]
        # )

        client = OpenAI(
            base_url='https://api-inference.modelscope.cn/v1/',
            api_key='d986cabb-c3de-42c8-ba7a-d124ed7dc5cd', # ModelScope Token
        )

        extra_body = {
            # enable thinking, set to False to disable 
            "enable_thinking": False,
            # use thinking_budget to contorl num of tokens used for thinking
            # "thinking_budget": 4096
        }

        response = client.chat.completions.create(
            model='Qwen/Qwen3-235B-A22B',  # ModelScope Model-Id
            messages=[
                {
                'role': 'user',
                'content': query
                }
            ],
            stream=False,
            extra_body=extra_body
        )
        return response.choices[0].message.content

    async def generate_ppt_content(self,topic: str,pages: int) -> str:
        # 输出格式
        output_format=json.dumps({
            "title":"example title",
            "pages":[
                {
                    "title": "title for page 1",
                    "content": [
                        {
                            "title": "title for paragraph 1",
                            "description": "detail for paragraph 1",
                        },
                        {
                            "title": "title for paragraph 2",
                            "description": "detail for paragraph 2",
                        },
                    ],
                },
                {
                    "title": "title for page 2",
                    "content": [
                        {
                            "title": "title for paragraph 1",
                            "description": "detail for paragraph 1",
                        },
                        {
                            "title": "title for paragraph 2",
                            "description": "detail for paragraph 2",
                        },
                        {
                            "title": "title for paragraph 3",
                            "description": "detail for paragraph 3",
                        },
                    ],
                },
            ],
        },ensure_ascii=True)
        
        # prompt
        prompt=f'''我要准备1个关于{topic}的PPT，要求一共写{pages}页，请你根据主题生成详细内容，不要省略。
        按这个JSON格式输出{output_format}，只能返回JSON，且JSON不要用```包裹，内容要用中文。'''

        #print(prompt)
        
        # 调用llm生成PPT内容
        ppt_content=json.loads(await self.chat_llm(prompt))

        return ppt_content
    
    # 生成PPT文件
    @staticmethod
    async def generate_ppt_file(topic,ppt_content):
        ppt=Presentation()
        
        # PPT首页
        slide=ppt.slides.add_slide(ppt.slide_layouts[0]) # title&subtitle layout
        slide.placeholders[0].text=ppt_content['title']
        
        # 内容页
        print('总共%d页...'%len(ppt_content['pages']))
        for i,page in enumerate(ppt_content['pages']):
            print('生成第%d页:%s'%(i+1,page['title']))
            slide=ppt.slides.add_slide(ppt.slide_layouts[1]) # title&content layout
            # 标题
            slide.placeholders[0].text=page['title']
            # 正文
            for sub_content in page['content']:
                print(sub_content)
                # 一级正文
                sub_title=slide.placeholders[1].text_frame.add_paragraph()
                sub_title.text,sub_title.level=sub_content['title'],1
                # 二级正文
                sub_description=slide.placeholders[1].text_frame.add_paragraph()
                sub_description.text,sub_description.level=sub_content['description'],2
        
        ppt.save('%s.pptx'%topic)

        return 'success'



AiPPTService: AiPPTServices = AiPPTServices()
    